package com.smile.cloud.zkConfig.distributedLock.zk;



import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * zookeeper 分布式锁实现
 */
@Data
@Slf4j
@Component
public class ZookeeperLocker implements ZKLocker {

    /**
     * zk 锁前缀
     */
    private final static String LOCKER_PREFIX = "/zk_lock/";

    @Autowired
    private ZookeeperClient zookeeperClient;


    @Override
    public <T> T lock(String resourceName, ZKAquiredLockWorker<T> worker) throws InterruptedException, UnableToZKAquireLockException, Exception {
        return lock(resourceName, worker, 10, TimeUnit.SECONDS);
    }

    @Override
    public <T> T lock(String resourceName, ZKAquiredLockWorker<T> worker, long lockTime, TimeUnit timeUnit) throws UnableToZKAquireLockException, Exception {
        String path = zookeeperClient.getZookeeperLockPath() + resourceName;
        //创建锁对象
        InterProcessMutex lock = new InterProcessMutex(zookeeperClient.getClient(), path);
        boolean success = false;
        try {
            //获取锁
            success = lock.acquire(lockTime, timeUnit);
            if (success) {
                return worker.invokeAfterLockAquire();
            }
        } finally {
            //释放锁
            if (success) {
                lock.release();
            }
        }
        return  null;
    }

}